<template>
  <div>
    <van-search
      v-model="value"
      placeholder="请输入搜索关键词"
      show-action
      background="#3296FA"
      @search="onSearch"
      @cancel="onCancel"
      @focus="isResultShow = false"
    />
    <search-result v-if="isResultShow" :search-text="value"></search-result>
    <search-suggestion @search="onSearch" v-else-if="value" :search-text="value"></search-suggestion>
    <search-history :searchHistories="searchHistories" v-else></search-history>
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchResult from './components/search-result.vue'
import SearchSuggestion from './components/search-suggestion.vue'
export default {
  name: 'SearchPage',
  props: {
  },
  data () {
    return {
      value: '',
      isResultShow: false, // 控制搜索结果的显示
      searchHistories: JSON.parse(localStorage.searchHistories || '[]')
    }
  },
  components: { SearchHistory, SearchResult, SearchSuggestion },
  created () {},
  mounted () {},
  watch: {
    searchHistories (val) {
      localStorage.searchHistories = JSON.stringify(val)
    }
  },
  methods: {
    // 输入框,点击回车
    onSearch (val) {
      if (val.trim() === '') return
      // 存储value
      this.value = val
      const index = this.searchHistories.findIndex(t => t === val)
      if (index !== -1) this.searchHistories.splice(index, 1)
      this.searchHistories.unshift(val)
      // 显示搜索结果组件
      this.isResultShow = true
    },
    onCancel () {
      console.log('取消')
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.van-search__action{
  color: #fff;
}
</style>
